<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\shouyin\model\Subscribe as SubscribeModel;
use app\shouyin\model\Operation as OperationModel;
use app\system\model\systemUser as systemUserModel;
use think\Db;
use app\user\model\User as UserModel;
use app\shop\model\Room as RoomModel;
use app\product\model\Project as ProjectModel;
use app\product\model\Unit as UnitModel;
use app\product\model\Product as ProductModel;
use app\product\model\ProjectProduct as ProjectProductModel;
use app\warehouse\model\Warehouse as WarehouseModel;
use think\facade\Cache;
use app\finance\model\Account as AccountModel;
use app\shouyin\model\UserBalanceLog as UserBalanceLogModel;
use app\shouyin\model\UserCardLog as UserCardLogModel;
use app\shouyin\model\UserCard as UserCardModel;
use app\shouyin\model\SubscribeProject as SubscribeProjectModel;
use app\finance\model\SystemBalanceLog as SystemBalanceLogModel;
/**
 *  预约单
 */
class Subscribe extends Admin
{
    protected $hisiModel = 'Subscribe';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];
            // if(ADMIN_ID != 1){
            $where['shop_id'] = session('shop_id');
            // }
            // 会员
            // $users = UserModel::getSelect(UserModel::all());
            // $this->assign('users', $users);
            $this->assign('users', UserModel::field('id,nick')->all());
            // 房间
            // $rooms = RoomModel::getSelect(RoomModel::where($where)->all());
            // $this->assign('rooms', $rooms);
            $this->assign('rooms', RoomModel::where($where)->all());
            // 顾问
            $admins = systemUserModel::where($where)->all();
            $advisers = [];
            $technician = [];
            $warehouse_admins = [];
            $cashiers = [];
            $finances = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }else if($value['type'] == '库管'){
                    $warehouse_admins[] = $value;
                }else if($value['type'] == '前台'){
                    $cashiers[] = $value;
                }else if($value['type'] == '财务'){
                    $finances[] = $value;
                }
            }

            $this->assign('finances', systemUserModel::getSelect($finances));
            // $this->assign('cashiers', systemUserModel::getSelect($cashiers));
            $this->assign('cashiers', $cashiers);
            // $this->assign('warehouse_admins', systemUserModel::getSelect($warehouse_admins));
            $this->assign('warehouse_admins', $warehouse_admins);
            // $this->assign('advisers', systemUserModel::getSelect($advisers));
            $this->assign('advisers', $advisers);
            $this->assign('technicians', $technician);
            $projects = ProjectModel::field('*, id as project_id, name as project_name')->all();
            $this->assign('projects', $projects);

            $this->assign('products', ProductModel::getSelect(ProductModel::all()));
            $warehouse= WarehouseModel::where('shop_id',session('shop_id'))->field('id,name,type')->all();
            $this->assign('warehouses',$warehouse);
            $products = ProductModel::where('status',1)->field('id,name,specs,unit_id, unit_id as unit_text,  decomposition_id,decomposition_id as decomposition_text,price2')->select();
            $this->assign('products',$products);
        }
        $account = AccountModel::getSelect(AccountModel::all());
        $this->assign('accounts',$account);
        // halt($account);

    }
    public function index()
    {
        $state     = $this->request->param('state');
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $sysUser = systemUserModel::column('id,nick');
            $where['shop_id'] = session('shop_id');
            if($state){
                $data['data'] = SubscribeModel::with(['hasShop','hasRoom','hasUser'])
                                ->where($where)
                                ->where('status',5)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
            }else{
                $data['data'] = SubscribeModel::with(['hasShop','hasRoom','hasUser'])
                                ->where($where)
                                ->where('status','<>',5)
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();
            }
            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['adviser'] = $sysUser[$data['data'][$key]['adviser_id']];
                $data['data'][$key]['technician'] = Db::name('system_user')->where('id','in',$data['data'][$key]['technician_ids'])->column('nick');
                $data['data'][$key]['projects'] = Db::name('project')->where('id','in',$data['data'][$key]['project_ids'])->column('name');
                $data['data'][$key]['cashier'] = Db::name('system_user')->where('id','in',$data['data'][$key]['cashier_id'])->column('nick');
                $data['data'][$key]['warehouse_admin'] = Db::name('system_user')->where('id','in',$data['data'][$key]['warehouse_admin'])->column('nick');
                $data['data'][$key]['finance'] = Db::name('system_user')->where('id','in',$data['data'][$key]['finance_id'])->column('nick');
                // $data['data'][$key]['cashier'] = Db::name('system_user')->where('id','in',$data['data'][$key]['cashier_id'])->column('nick');
            }

            $data['count'] = SubscribeModel::where($where)->count('id');
            $data['code'] = 0;
            return json($data);

        }
        if($state){
            $this->assign('state',$state);
            return $this->fetch();
        }else{
            return $this->fetch('operation');
        }

    }

    public function add()
    {
        if($this->request->isPost()){
            $postData = $this->request->post();
            // Db::startTrans();
            // try {

                if($postData['user_id'] == ''){
                    return $this->axiosMsg("预约会员不能为空", false);
                }
                if($postData['adviser_id'] == ''){
                    return $this->axiosMsg("预约顾问不能为空", false);
                }
                if($postData['project_ids'] == ''){
                    return $this->axiosMsg("预约项目不能为空", false);
                }
                $postData['appointment_time'] = date('Y-m-d H:i:s',$postData['appointment']);
                $postData['sn'] = create_order_sn();

                $postData['shop_id'] = session('shop_id');
                $SubscribeModel = new SubscribeModel;
                if(!$SubscribeModel->save($postData)){
                    return $this->axiosMsg('提交失败，请重试',false);
                }

            // } catch (Exception $e) {
            //     return $this->axiosMsg($e->getMessage(),false);
            // }
            return $this->axiosMsg('提交成功',true);
            // halt($postData);
        }
        return $this->fetch();
    }

    /**
     * 开单，谁都可以操作， 不做限制
     */
    public function kaidan()
    {

        $id = $this->request->param('id/a');
        if (empty($id)) {
            return $this->error('缺少id参数');
        }
        $subscribeInfo = SubscribeModel::get($id);
        if($subscribeInfo->status == 2){
            return $this->error('预约单已经开单！');
        }else if($subscribeInfo->status == 3){
            return $this->error('预约单无效！');
        }
         Db::startTrans();
        try {
        // 更新预约单状态
            $subscribeInfo->status = 0;
            

            $projects = Db::name('project')->where('id','in',$subscribeInfo->project_ids)->select();
            // halt($projects);
            foreach ($projects as $key => $value) {
                $pros[] = [
                    'project_id' => $value['id'], 
                    'project_name' => $value['name'], 
                    'is_give' => 1, 
                    'price' => $value['price'], 
                    'technician_ids' => $subscribeInfo->technician_ids, 
                    'adviser_id' => $subscribeInfo->adviser_id, 
                    'bak' => '', 
                    'type' => 1,  //项目分类:1=实操项目,2=特殊项目
                    'num' => 1, 
                    'settlement' => 1,  // 结算方式：1=现金消费，2=储值卡，3=赠送，4=疗程卡
                    'shougong' => 0
                ];
            }
            $subscribeInfo->project_data = json_encode($pros,true);
            $res = $subscribeInfo->save();
            // Db::name('subscribe_project')->insertAll($pros);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            // return $this->axiosMsg($e->getMessage(),false);
             return $this->error('开单失败:'.$e->getMessage());
        }

        return $this->success('开单成功');
    }
    /**
     * 顾问开单
     * @author qinty.net <282512951@qq.com>
     * @return mixed
     */
    public function gwkd()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {
                if($postData['adviser_id'] == ''){
                    return $this->axiosMsg('审核顾问不能能为空',false);
                }
                $postData['project_data'] = json_encode($postData['project_data']);
                $postData['status'] = 1;
                // echo $model->save($postData, $where)
                if ($model->save($postData, $where) === false) {
                    return $this->axiosMsg($model->getError(),false);
                }
                return $this->axiosMsg('保存成功',true);
            }

            $formData = $model->where($where)->find();

        } 
        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);
        // $project_data = Db::name('subscribe_project')->where('sub_id',$formData['id'])->select();
        $this->assign('project_data', json_decode($formData->project_data));
        // halt($project_data);
        $template = $this->request->param('template', 'form');

        return $this->fetch('gwkd');
    }

    /**
     * 库管开单
     */
    public function kgkd()
    {

        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
           
        }

        $where = [];

        $model = $this->model();

        $pk = $model->getPk();
        $id = $this->request->param($pk);
        $where[]= [$pk, '=', $id];
        $where  = $this->getRightWhere($where);
        if ($this->request->isPost()) {
            if(!isset($postData['warehouse_admin']) || empty($postData['warehouse_admin'])){
                return $this->axiosMsg('库管为必填项',false);
            }
            $product_data = $postData['product_data'];
            $postData['product_data'] = json_encode($postData['product_data']);
            if($model->save($postData, $where) === false){
                return $this->axiosMsg($e->getError(),false);
            }
            
            return $this->axiosMsg('提交成功', true);
        }

        $formData = $model->where($where)->find();
        $project_data = json_decode($formData['project_data'],true);
        $product_data = [];
        foreach ($project_data as $key => $value) {
            // $product_data[] = Db::name('project_product')->where('project_id',$value['project_id'])->select();
            $project_data[$key]['product'] = ProJectProductModel::alias('pp')
            ->join('product p','p.id=pp.product_id')
            ->field('pp.*,p.unit_id,p.decomposition_id')
            ->where('project_id',$value['project_id'])
            ->select();
        }
        $unit = Db::name('unit')->column('id,name');
        foreach ($project_data as $key => $value) {
            foreach ($project_data[$key]['product'] as $k => $v) {
                $project_data[$key]['product'][$k]['unit_text'] = $unit[$v['unit_id']];
                $project_data[$key]['product'][$k]['decomposition_text'] = $unit[$v['decomposition_id']];
            }
        }
        // halt($project_data);
        $this->assign('project_data', $project_data);
        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        return $this->fetch();
    }


    /**
     * 获取项目默认需要使用的产品
     */
    public function getTempProduct()
    {
        $sub_id = $this->request->param('sub_id');
        // halt(Cache::has('products_'.$sub_id));
        if( !Cache::has('products_'.$sub_id) || empty(Cache::get('products_'.$sub_id))){
            $unit = UnitModel::column('id,name');
            $projects['data'] = Db::name('subscribe_project')->alias('sp')
            ->join('hisi_project_product pp','sp.project_id = pp.project_id')
            ->join('hisi_product p','p.id=pp.product_id')
            ->join('project pj', 'pj.id=sp.project_id')
            ->where('sub_id',$sub_id)
            ->field('sp.sub_id, sp.project_id, num as project_num, p.id as product_id, (pp.category_number*num) as product_num,is_volume, unit_id,decomposition_id,p.name as product_name,pj.name as project_name')
            ->select();

            foreach ($projects['data'] as $key => $value) {
                $projects['data'][$key]['unit'] = $unit[$projects['data'][$key]['unit_id']];
                $projects['data'][$key]['decomposition'] = $unit[$projects['data'][$key]['decomposition_id']];
            }

                Cache::set('products_'.$sub_id, $projects['data']);
        }else{
            $projects['data'] = Cache::get('products_'.$sub_id);
        }

        $projects['code'] = 0;
        return json($projects);
    }

    /**
     * 库管配料，暂时没做
     */
    public function addProduct()
    {
        $editData = [];
        $editData['sub_id'] = $this->request->param('sub_id');
        $editData['project_id'] = $this->request->param('project_id');
        $editData['project_name'] = Db::name('project')->where('id',$editData['project_id'])->value('name');
        $projects = Db::name('subscribe_project')->where('sub_id', $editData['sub_id'])->field('project_id,num')->find();
        // $sp = Db::name('subscribe_project')->where()
        // halt($projects);
        $this->assign('formData',$editData);
        return $this->fetch('product_form');
    }

    /**
     * 库管配料，编辑配料
     */
    public function editProduct()
    {
        $product_id = $this->request->param('product_id');
        $sub_id = $this->request->param('sub_id');
        $project_id = $this->request->param('project_id');

        $unit = UnitModel::column('id,name');
        if($this->request->isPost()){
            $postData = $this->request->post();
            if(!$postData['product_id']){
                return $this->error('产品参数错误！');
            }
            $productInfo = ProductModel::get($product_id);
            $postData['product_name'] = $productInfo->name;
            $postData['unit_id'] = $productInfo->unit_id;
            $postData['unit'] = $unit[$productInfo->unit_id];
            $postData['decomposition_id'] = $productInfo->decomposition_id;
            $postData['decomposition'] = $unit[$productInfo->decomposition_id];

        }

        $data = Cache::get('products_'.$sub_id);
        $editData = [];
        $unset = '';
        foreach ($data as $key => $value) {
                if($this->request->isPost()){
                    if($value['sub_id'] == $sub_id && $value['project_id'] == $project_id && $value['product_id'] == $this->request->param('product_id_old')){
                        $unset = $key;
                    }
                }else{
                    if($value['sub_id'] == $sub_id && $value['project_id'] == $project_id && $value['product_id'] == $product_id){
                        $editData = $value;
                    }
                }
        }

        if($this->request->isPost()){
            // halt($unset);
            unset($data[$unset]);
            unset($postData['product_id_old']);
            $data[] = $postData;
            Cache::set('products_'.$sub_id, $data);
            // halt(Cache::get('products_'.$sub_id));
            return $this->success('保存成功', '');
        }
        $editData['product_id_old'] = $editData['product_id'];
        $this->assign('formData',$editData);
        return $this->fetch('product_form');
    }

    /**
     * 库管配料，删除配料
     */
    public function delProduct()
    {
        $product_id = $this->request->param('product_id');
        $sub_id = $this->request->param('sub_id');
        $project_id = $this->request->param('project_id');
        $data = Cache::get('products_'.$sub_id);
        $editData = [];
        $unset = '';
        foreach ($data as $key => $value) {
            if($value['sub_id'] == $sub_id && $value['project_id'] == $project_id && $value['product_id'] == $product_id){
                $unset = $key;
            }
        }
        unset($data[$unset]);
        Cache::set('products_'.$sub_id, $data);
        return $this->success('删除成功', '');
    }

    /**
     * 收银结算
     */
    public function sykd()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {
                // 启动事务
                Db::startTrans();
                try {
                 if($postData['status'] == 3){  // 提交财务审核以后，生成进账流水 收银结算
                     $SubscribeProject = new SubscribeProjectModel;
                     // 该操作单下的项目
                     $projects = $SubscribeProject->where('sub_id',$postData['id'])->select();
                     // 用户id
                     $user_id = Db::name('subscribe')->where('id',$postData['id'])->value('user_id');
                     // halt($projects);
                     if(!empty($projects)){
                         $cards = [];
                         // 判断会员卡是够够用
                         foreach ($projects as $key => $value) {
                             if($value['settlement'] == 4){
                                 $cards[$value['project_id']][] = $value['num'];
                             }
                         }
                         foreach ($cards as $key => $value) {
                             $project_num = Db::name('user_card_log')->where('user_id',$user_id)->where('pid',$key)->where('use',1)->where('type',1)->count('id');
                             if(array_sum($cards[$key]) > $project_num  || $project_num == 0){
                                 throw new \Exception("用户会员卡不足！");
                                 // return $this->axiosMsg('用户会员卡不足！', false);
                             }
                         }
                         // 检查余额是否够用
                         if($postData['account_id'] == 0){
                             // 用户余额
                             $userBalanceJia  = UserBalanceLogModel::where('user_id',$user_id)->where('type',1)->sum('price');
                             $userBalanceJian  = UserBalanceLogModel::where('user_id',$user_id)->where('type','<>',1)->sum('price');
                             $userBalance = $userBalanceJia - $userBalanceJian;
                             // 项目总价格
                             $priceSum = $SubscribeProject->where('sub_id',$postData['id'])->where('is_give',1)->where('settlement',1)->sum('price');
                             if($userBalance < $priceSum){
                                 throw new \Exception('余额不足');
                             }
                         }


                     }
                     $UserCardLogModel = new UserCardLogModel;
                     $UserBalanceLogModel = new UserBalanceLogModel;
                     $SystemBalanceLogModel = new SystemBalanceLogModel;
                     $ins = [];
                     foreach ($projects as $key => $value) {
                         if($value['settlement'] == 4){
                             $project_ids = UserCardLogModel::where('user_id',$user_id)->where('pid',$value['project_id'])->where('use',1)->where('type',1)->limit($value['num'])->column('id');
                             $UserCardLogModel->where('id','in',$project_ids)->update(['use'=>2,'use_sn'=>$postData['sn']]);
                         }else if($value['settlement'] == 1){
                             if($postData['account_id'] == 0){
                                 // 项目总价格
                                 $ins[] = [
                                     'user_id' => $user_id,
                                     'type' => 2, // 购买项目使用
                                     'price' => $value['price'],
                                     'sn' => $postData['sn'],
                                 ];

                             }else{

                                 // 现金支付方式
                                 $ins[] = [
                                     'sn' => $postData['sn'],
                                     'type' => 1,  // 项目收入
                                     'account_id' => $postData['account_id'],
                                     'price' => $value['price'] ,
                                 ];
                             }
                         }
                     }
                     // 结算减库存
                     Db::name('stock')->where('sn',$postData['sn'])->update(['status'=>1]);
                      if($postData['account_id'] == 0){
                             $UserBalanceLogModel->saveAll($ins);
                         }else{
                              $SystemBalanceLogModel->saveAll($ins);
                         }

                 }
                 // throw new \Exception('xxx');
                $model->save($postData, $where);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
                return $this->success('保存成功', '');
            }

            $formData = $model->where($where)->find();

        }  else {

            return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

        }

        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        // 需要支付的金额（使用会员卡的不计入在内）
        $formData['price'] = Db::name('subscribe_project')->where('sub_id',$formData['id'])->where('is_give',1)->where('settlement',1)->sum('price');
        $this->assign('formData', $formData);
        // 用户余额
        $userBalanceJia  = UserBalanceLogModel::where('user_id',$formData['user_id'])->where('type',1)->sum('price');
        $userBalanceJian  = UserBalanceLogModel::where('user_id',$formData['user_id'])->where('type','<>',1)->sum('price');
        $userBalance = $userBalanceJia - $userBalanceJian;
        $this->assign('userBalance',$userBalance);
        // 用户购买的会员卡
        $userCards = [];
        $userCards = Db::name('user_card_log')->alias('ucl')->join('project p', 'p.id=ucl.pid')->field('name,count(ucl.id) as num')->where('user_id',$formData['user_id'])->where('ucl.type',1)->group('pid')->where('use',1)->select();
        $this->assign('userCards',$userCards);
        $template = $this->request->param('template', 'form');
        return $this->fetch();
    }

    public function cwsh()
    {
        $where = [];
        // if ($this->hisiModel) {// 通过Model更新
        if($this->hisiModel){
            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[]= [$pk, '=', $id];
            $where  = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                $postData = $this->request->post();

                if ($model->save($postData, $where) === false) {
                    return $this->error($model->getError());
                }

                return $this->success('保存成功', '');
            }
            $formData = $model->where($where)->find();
        }



        $formData['price'] = Db::name('subscribe_project')->where('sub_id',$formData['id'])->where('is_give',1)->where('settlement',1)->sum('price');
        $this->assign('formData', $formData);
        return $this->fetch();
    }
}
